package cn.qicaiwang.open.app.controller;




import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.regex.Pattern;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;

@RestController
@RequestMapping("/qcwapp/douyin")
public class DouyinDownloadController {

    private static final Logger logger = LoggerFactory.getLogger(DouyinDownloadController.class);

    /**
     * 解析并下载抖音无水印视频
     * @param shareLink 抖音分享链接或文本
     * @return 下载结果
     */
    @PostMapping("/download")
    public ResponseEntity<Map<String, Object>> downloadNoWatermarkVideo(@RequestParam String shareLink) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 从分享文本中提取纯净URL
            String pureUrl = extractPureUrl(shareLink);
            if (pureUrl == null || pureUrl.isEmpty()) {
                result.put("success", false);
                result.put("message", "无法从输入中提取有效的抖音链接");
                return ResponseEntity.badRequest().body(result);
            }

            // 2. 获取视频ID
            String videoId = getVideoId(pureUrl);
            if (videoId == null || videoId.isEmpty()) {
                result.put("success", false);
                result.put("message", "无法从链接中提取视频ID");
                return ResponseEntity.badRequest().body(result);
            }

            // 3. 构造无水印视频地址
            String noWatermarkUrl = "https://m.douyin.com/share/video/" + videoId;
            String finalVideoUrl = getNoWatermarkVideoUrl(noWatermarkUrl);
            if (finalVideoUrl == null || finalVideoUrl.isEmpty()) {
                result.put("success", false);
                result.put("message", "无法获取无水印视频地址");
                return ResponseEntity.badRequest().body(result);
            }

            // 4. 下载视频
            String filePath = downloadVideo(finalVideoUrl, "抖音无水印视频");
            if (filePath == null || filePath.isEmpty()) {
                result.put("success", false);
                result.put("message", "视频下载失败");
                return ResponseEntity.internalServerError().body(result);
            }

            // 5. 返回成功结果
            result.put("success", true);
            result.put("message", "视频下载成功");
            result.put("filePath", filePath);
            result.put("videoUrl", finalVideoUrl);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("抖音视频下载出错", e);
            result.put("success", false);
            result.put("message", "处理过程中发生错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 从分享文本中提取纯净URL
     */
    private String extractPureUrl(String shareText) {
        // 匹配抖音短链接格式
        Pattern pattern = Pattern.compile("https?://v\\.douyin\\.com/\\w+/");
        Matcher matcher = pattern.matcher(shareText);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    /**
     * 获取视频ID
     */
    private String getVideoId(String url) throws IOException {
        Connection con = Jsoup.connect(url);
        con.header("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
        Connection.Response resp = con.method(Connection.Method.GET).execute();
        String strUrl = resp.url().toString();

        // 从重定向后的URL中提取视频ID
        int startIndex = strUrl.indexOf("video/");
        if (startIndex == -1) return null;

        int endIndex = strUrl.lastIndexOf("/");
        if (endIndex <= startIndex) return null;

        return strUrl.substring(startIndex, endIndex).replace("video/", "");
    }

    /**
     * 获取无水印视频地址
     */
    private String getNoWatermarkVideoUrl(String url) throws IOException {
        // 这里需要实现获取无水印视频地址的逻辑
        // 实际实现可能需要调用第三方API或解析页面
        // 以下是示例代码，实际可能需要调整

        Connection con = Jsoup.connect(url);
        con.header("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
        Document doc = con.get();

        // 解析页面获取无水印视频地址
        // 实际选择器需要根据抖音页面结构调整
        Element videoElement = doc.selectFirst("video source");
        if (videoElement != null) {
            return videoElement.attr("src");
        }
        return null;
    }

    /**
     * 下载视频到本地
     */
    private String downloadVideo(String videoAddress, String desc) {
        try {
            // 确保地址有https前缀
            if (!videoAddress.startsWith("http")) {
                videoAddress = "https:" + videoAddress;
            }

            // 创建保存目录
            String baseDir = "C:/data/douyin";
            File dir = new File(baseDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString().replace("-", "") + ".mp4";
            String filePath = baseDir + File.separator + fileName;

            // 下载视频
            URL url = new URL(videoAddress);
            try (InputStream in = url.openStream();
                 FileOutputStream out = new FileOutputStream(filePath)) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }

            logger.info("视频保存路径: {}", filePath);
            return filePath;

        } catch (IOException e) {
            logger.error("视频下载失败", e);
            return "";
        }
    }


}